import { watch, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'

export function useEcharts(option: any) {
  let chartInstance: any = null

  // 初始化
  const initChart = (el: HTMLElement | null) => {
    if (!el) return
    chartInstance = echarts.init(el)
    chartInstance.setOption(option.value)
  }

  // 响应式更新 option
  watch(
    () => option.value,
    (newoption) => {
      if (chartInstance) {
        nextTick(() => {
          chartInstance.resize()
          chartInstance.setOption(newoption, true)
        })
      }
    }
  )

  // 重新设置 option
  const setOption = () => {
    if (chartInstance) {
      nextTick(chartInstance.setOption(option.value, true))
    }
  }

  onUnmounted(() => {
    if (chartInstance) {
      chartInstance.dispose()
      chartInstance = null
    }
  })

  return { initChart, setOption }
}
